import React, { useState, useEffect } from 'react';
import { Form, Button, Toast, Spin } from '@douyinfe/semi-ui';
import { useNavigate, useParams } from 'react-router-dom';
import axiosInstance from './axiosInstance';

interface UserData {
  id?: string;
  phone: string;
  status?: number;
  channelId?: number;
}

/**
 * 用户表单组件
 * 用于创建和编辑用户
 */
const UserForm: React.FC = () => {
  const navigate = useNavigate();
  const { id, channelId } = useParams(); // 获取路由参数中的用户ID和channelId
  const [loading, setLoading] = useState(false);
  const [userData, setUserData] = useState<UserData | null>(null);
  const [formData, setFormData] = useState({ phone: '' });
  
  // 判断是编辑模式还是创建模式
  const isEditMode = !!id;

  /**
   * 加载用户数据（编辑模式）
   */
  const loadUserData = async () => {
     if (!id) return;
     
     try {
       setLoading(true);
       const response = await axiosInstance.post('/lowcode3user/user/findOne', {
         id: id,
         channelId: channelId
       });
       if (response.data.errorCode === '0') {
         const user = response.data.data;
         setUserData(user);
         // 设置表单初始值
         setFormData({
           phone: user.phone
         });
       } else {
         Toast.error('加载用户数据失败');
         navigate(`/${channelId}/users`);
       }
     } catch (error) {
       Toast.error('加载用户数据失败');
       navigate(`/${channelId}/users`);
     } finally {
       setLoading(false);
     }
   };

  useEffect(() => {
    if (isEditMode) {
      loadUserData();
    }
  }, [id]);

  /**
   * 处理表单提交
   * @param values 表单数据
   */
  const handleSubmit = async (values: any) => {
    try {
      if (isEditMode) {
         // 编辑模式
         const requestData = {
           id: id,
           channelId: channelId ? parseInt(channelId, 10) : undefined,
           phone: values.phone
         };
         
         const response = await axiosInstance.post('/lowcode3user/user/updateUser', requestData);
         if (response.data.errorCode === '0') {
           Toast.success('更新成功');
           navigate(`/${channelId}/users`);
         } else {
           Toast.error(response.data.value || '更新失败');
         }
       } else {
        // 创建模式
        if (!channelId) {
          Toast.error('缺少channelId参数');
          return;
        }

        const requestData = {
          phone: values.phone,
          channelId: parseInt(channelId, 10)
        };

        const response = await axiosInstance.post('/lowcode3user/user/createUser', requestData);
        if (response.data.errorCode === '0') {
          Toast.success('创建成功');
          navigate(`/${channelId}/users`);
        } else {
          Toast.error(response.data.value || '创建失败');
        }
      }
    } catch (error) {
      Toast.error(isEditMode ? '更新失败' : '创建失败');
      console.error(isEditMode ? '更新用户失败:' : '创建用户失败:', error);
    }
  };

  if (loading) {
    return <Spin size="large" style={{ display: 'block', textAlign: 'center', marginTop: '50px' }} />;
  }

  return (
    <div style={{ maxWidth: '600px', margin: '0 auto' }}>
      <h2>{isEditMode ? '编辑用户' : '创建用户'}</h2>
      <Form onSubmit={handleSubmit} initValues={formData}>
        <Form.Input
          field="phone"
          label="手机号码"
          placeholder="请输入手机号码"
          initValue={formData.phone}
          rules={[
            { required: true, message: '请输入手机号码' },
            { pattern: /^1[3-9]\d{9}$/, message: '请输入有效的手机号码' }
          ]}
        />
        <div style={{ marginTop: '20px' }}>
          <Button type="primary" htmlType="submit" theme="solid">
            {isEditMode ? '更新用户' : '创建用户'}
          </Button>
          <Button 
            type="tertiary"
            style={{ marginLeft: '12px' }}
            onClick={() => {
              navigate(`/${channelId}/users`);
            }}
          >
            取消
          </Button>
        </div>
      </Form>
    </div>
  );
};

export default UserForm;